package com.atguigu.tingshu.search.service.impl;

import cn.hutool.core.lang.Assert;
import com.atguigu.tingshu.album.AlbumFeignClient;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.model.album.BaseCategoryView;
import com.atguigu.tingshu.search.service.ItemService;
import com.atguigu.tingshu.user.client.UserFeignClient;
import com.atguigu.tingshu.vo.album.AlbumStatVo;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class ItemServiceImpl implements ItemService {


    @Autowired
    private AlbumFeignClient albumFeignClient;

    @Autowired
    private UserFeignClient userFeignClient;


    @Autowired
    private Executor threadPoolTaskExecutor;

    @Autowired
    private RedissonClient redissonClient;

    /**
     * 根据专辑ID获取渲染详情页面专辑相关信息
     *
     * @param albumId
     * @return {"announcer":{主播对象},"albumInfo":{专辑信息},"albumStatVo":{统计对象},"baseCategoryView":{分类对象}}
     */
    @Override
    public Map<String, Object> getAlbumPageData(Long albumId) {

        //0.验证查询专辑ID是否为合法值，采用布隆过滤器
        RBloomFilter<Long> bloomFilter = redissonClient.getBloomFilter(RedisConstant.ALBUM_BLOOM_FILTER);
        if (!bloomFilter.contains(albumId)) {
            throw new GuiguException(404, "专辑:"+albumId+"不存在");
        }

        //1.创建响应结果Map对象:多线程对HashMap（线程不安全）进行并发写操作导致key被覆盖，造成死循环
        //故采用线程安全Map集合-ConcurrentHashMap
        Map<String, Object> map = new ConcurrentHashMap<>();

        //2.封装专辑基本信息
        CompletableFuture<AlbumInfo> albumInfoCompletableFuture = CompletableFuture.supplyAsync(() -> {
            AlbumInfo albumInfo = albumFeignClient.getAlbumInfo(albumId).getData();
            Assert.notNull(albumInfo, "专辑{}不存在！", albumId);
            map.put("albumInfo", albumInfo);
            return albumInfo;
        }, threadPoolTaskExecutor);

        //3.封装专辑统计信息
        CompletableFuture<Void> albumStatVoCompletableFuture = CompletableFuture.runAsync(() -> {
            AlbumStatVo albumStatVo = albumFeignClient.getAlbumStatVo(albumId).getData();
            Assert.notNull(albumStatVo, "统计信息{}不存在！", albumId);
            map.put("albumStatVo", albumStatVo);
        }, threadPoolTaskExecutor);


        //4.封装专辑分类信息
        CompletableFuture<Void> baseCategoryViewCompletableFuture = albumInfoCompletableFuture.thenAcceptAsync(albumInfo -> {
            BaseCategoryView categoryView = albumFeignClient.getCategoryView(albumInfo.getCategory3Id()).getData();
            Assert.notNull(categoryView, "分类{}不存在！", albumInfo.getCategory3Id());
            map.put("baseCategoryView", categoryView);
        }, threadPoolTaskExecutor);

        //5.封装主播信息
        CompletableFuture<Void> announcerCompletableFuture = albumInfoCompletableFuture.thenAcceptAsync(albumInfo -> {
            UserInfoVo userInfoVo = userFeignClient.getUserInfoVo(albumInfo.getUserId()).getData();
            Assert.notNull(userInfoVo, "用户{}不存在！", albumInfo.getUserId());
            map.put("announcer", userInfoVo);
        }, threadPoolTaskExecutor);


        //6.返回封装专辑相关信息Map对象
        //6.1 组合异步任务
        CompletableFuture.allOf(
                albumInfoCompletableFuture,
                albumStatVoCompletableFuture,
                baseCategoryViewCompletableFuture,
                announcerCompletableFuture
        ).join();
        return map;
    }
}
